/*
 * Copyright 2022-2023 the original author(https://github.com/wj596)
 * 
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * </p>
 */
package org.jsets.fastboot.flowable.component;

import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.common.engine.impl.cfg.TransactionState;
import org.flowable.common.engine.impl.event.FlowableEntityEventImpl;
import org.flowable.task.service.impl.persistence.entity.TaskEntityImpl;
import org.jsets.fastboot.flowable.service.IFlowTaskService;
import org.jsets.fastboot.flowable.service.impl.FlowEngineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;

/**
 * 
 * 全局监听
 * 
 * @author wangjie
 *
 */
@Slf4j
@Component
public class GlobalEventListener implements FlowableEventListener  {
	
	@Override
	public void onEvent(FlowableEvent event) {
		//System.out.println("ssssssssssssssss");
		FlowableEngineEventType eventType = (FlowableEngineEventType)event.getType();
		switch (eventType) {
		case PROCESS_STARTED:
//			ProcessStartedEvent startedEvent = new ProcessStartedEvent();
//			startedEvent.getProcessKey();
			
//			startedEvent.setExecutionId(eventImpl.getExecutionId());
//			startedEvent.setProcessInstanceId(eventImpl.getProcessInstanceId());
//			startedEvent.setProcessDefinitionId(eventImpl.getProcessDefinitionId());
//			startedEvent.setProcessKey(eventImpl.getProcessDefinitionId().split(":")[0]);
//			startedEvent.setStartedTime(DateUtils.format(new Date()));
//			log.info("流程[{}]开始", startedEvent.getProcessKey());
//			EventBus.post(startedEvent); //发布事件
			break;
		case PROCESS_COMPLETED:
//			ProcessCompletedEvent completedEvent = new ProcessCompletedEvent();
//			completedEvent.setExecutionId(eventImpl.getExecutionId());
//			completedEvent.setProcessInstanceId(eventImpl.getProcessInstanceId());
//			completedEvent.setProcessDefinitionId(eventImpl.getProcessDefinitionId());
//			completedEvent.setProcessKey(eventImpl.getProcessDefinitionId().split(":")[0]);
//			completedEvent.setCompletedTime(DateUtils.format(new Date()));
//			log.info("流程[{}]办结", completedEvent.getProcessKey());
//			EventBus.post(completedEvent); //发布事件
			break;
		case TASK_CREATED:
//			TaskCreatedEvent createdEvent = new TaskCreatedEvent();
//			createdEvent.setExecutionId(eventImpl.getExecutionId());
//			createdEvent.setProcessInstanceId(eventImpl.getProcessInstanceId());
//			createdEvent.setProcessDefinitionId(eventImpl.getProcessDefinitionId());
//			createdEvent.setProcessKey(eventImpl.getProcessDefinitionId().split(":")[0]);
//			createdEvent.setCreatedTime(DateUtils.format(new Date()));
	//		if (getFlowableEntity(event) instanceof TaskEntityImpl) {
	//			TaskEntityImpl entityImpl = (TaskEntityImpl) getFlowableEntity(event);
//				createdEvent.setTaskId(entityImpl.getId());
				///createdEvent.setTaskName(entityImpl.getName());
	//			System.out.println("===========TASK_CREATED=========");
	//			System.out.println(entityImpl.getName());
	//			try {
	//				Thread.sleep(1000l);
	//			} catch (InterruptedException e) {
					// TODO Auto-generated catch block
	//				e.printStackTrace();
		//		}
				//System.out.println("===========TASK_CREATED=========");
//				createdEvent.setTaskDefId(entityImpl.getTaskDefinitionKey());
//				log.info("任务[{}]创建", createdEvent.getTaskName());
			//}
//			EventBus.post(createdEvent); //发布事件
			break;
		case SEQUENCEFLOW_TAKEN:
//			SequenceflowTakenEvent takenEvent = new SequenceflowTakenEvent();
//			takenEvent.setExecutionId(eventImpl.getExecutionId());
//			takenEvent.setProcessInstanceId(eventImpl.getProcessInstanceId());
//			takenEvent.setProcessDefinitionId(eventImpl.getProcessDefinitionId());
//			String processKey = eventImpl.getProcessDefinitionId().split(":")[0];
//			takenEvent.setProcessKey(processKey);
//			takenEvent.setCreatedTime(DateUtils.format(new Date()));
//			if(event instanceof FlowableSequenceFlowTakenEventImpl) {
//				FlowableSequenceFlowTakenEventImpl takenEventImpl = (FlowableSequenceFlowTakenEventImpl)event;
//				takenEvent.setSequenceFlowId(takenEventImpl.getId());
//				takenEvent.setSourceActivityId(takenEventImpl.getSourceActivityId());
//				takenEvent.setSourceActivityName(takenEventImpl.getSourceActivityName());
//				takenEvent.setTargetActivityId(takenEventImpl.getTargetActivityId());
//				takenEvent.setTargetActivityName(takenEventImpl.getTargetActivityName());
//			}
//			EventBus.post(takenEvent); //发布事件
			break;
		case TIMER_FIRED:
			
			break;
		default:
			break;
		}
		
		
		
	}

	/**
	 * onEvent(..)方法抛出异常时的行为
	 * 若返回false，忽略异常
	 * 若返回true，异常不会被忽略而会被上抛，使当前执行的命令失败。
	 */
	@Override
	public boolean isFailOnException() {
		return false;
	}

	@Override
	public boolean isFireOnTransactionLifecycleEvent() {
		return true;
	}

	@Override
	public String getOnTransaction() {
		return TransactionState.COMMITTED.name();
	}
	
	private Object getFlowableEntity(FlowableEvent event) {
		org.flowable.engine.delegate.event.impl.FlowableEntityEventImpl delegateEventImpl = null;
		org.flowable.common.engine.impl.event.FlowableEntityEventImpl engineEventImpl = null;
		if (event instanceof org.flowable.engine.delegate.event.impl.FlowableEntityEventImpl) {
			delegateEventImpl = (org.flowable.engine.delegate.event.impl.FlowableEntityEventImpl) event;
			return delegateEventImpl.getEntity();
		} else {
			engineEventImpl = (org.flowable.common.engine.impl.event.FlowableEntityEventImpl) event;
			return engineEventImpl.getEntity();
		}
		
	}

}